﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SiGeSIB.Data.Providers;
using System.Data.SqlClient;
using System.Data;
using SiGeSIB.Data.Common;

namespace SiGeSIB.Data.Specialized.Providers
{
	public class BackupRestorationDataProvider : BaseDataProvider, IBackupRestorationDataProvider
	{
		#region IBackupRestorationDataProvider Members

		public void Backup(string fileName)
		{
			try
			{
				using (SqlConnection conn = _ConfigMgr.CreateConnection())
				{
					conn.ChangeDatabase("master");

					using (SqlCommand cmd = conn.CreateCommand())
					{
						cmd.CommandType = CommandType.Text;
						cmd.CommandText = string.Format("BACKUP DATABASE SIGESIB TO DISK = '{0}' WITH COPY_ONLY", fileName);

						cmd.ExecuteNonQuery();
					}
				}
			}
			catch (Exception e)
			{
                if (e.Message.Contains("Cannot open"))
                    throw new ValidationError(null, "Não foi possível acessar a pasta selecionada. Escolha outra pasta.");
                else
                    throw new DbException("Erro na comunicação com o banco de dados.");
			}
		}

		public void RestoreBackup(string fileName)
		{
			try
			{
				using (SqlConnection conn = _ConfigMgr.CreateConnection())
				{
					conn.ChangeDatabase("master");

					using (SqlCommand cmd = conn.CreateCommand())
					{
						cmd.CommandType = CommandType.Text;
						cmd.CommandText = string.Format(
@"
BEGIN TRY
IF EXISTS(SELECT name FROM sys.databases WHERE name = 'SIGESIB')
ALTER DATABASE SIGESIB
SET SINGLE_USER WITH
ROLLBACK IMMEDIATE

RESTORE DATABASE [SIGESIB] FROM  DISK = N'{0}'
END TRY
BEGIN CATCH
ROLLBACK TRAN
ALTER DATABASE SIGESIB
SET MULTI_USER WITH
ROLLBACK IMMEDIATE
END CATCH", fileName);

						cmd.ExecuteNonQuery();
					}
				}
			}
			catch (Exception)
			{
				throw new DbException("Erro na comunicação com o banco de dados.");
			}
		}

		#endregion
	}
}
